<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-form">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="数据库名称">
          <el-input v-model="queryParams.dbName" placeholder="请输入数据库名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="tool-bar">
      <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      <el-button type="primary" icon="el-icon-edit" :disabled="selection.length !== 1" @click="handleUpdate">修改</el-button>
      <el-button type="danger" icon="el-icon-delete" :disabled="selection.length === 0" @click="handleDelete">删除</el-button>
      <el-button type="info" icon="el-icon-download" @click="handleExport">导出</el-button>
    </div>

    <!-- 表格数据展示区域 -->
    <el-table v-loading="loading" :data="databaseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品ID" prop="productId" width="100" align="center" />
      <el-table-column label="数据库名称" prop="dbName" align="left" />
      <el-table-column label="图标" prop="icon" width="120" align="center">
        <template slot-scope="scope">
          <img v-if="scope.row.icon" :src="scope.row.icon" style="width: 40px; height: 40px;" alt="图标" />
          <span v-else>无图标</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" prop="type" align="center" />
      <el-table-column label="数据库描述" prop="description" align="left" :show-overflow-tooltip="true" />
      <el-table-column label="备注" prop="remark" align="left" :show-overflow-tooltip="true" />
      <el-table-column label="操作" prop="" width="150" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="handleRemove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-show="total > 0"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/修改对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px" @close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="数据库名称" prop="dbName">
          <el-input v-model="form.dbName" placeholder="请输入数据库名称" />
        </el-form-item>
        <el-form-item label="图标">
          <div class="upload-container">
            <el-upload
              class="avatar-uploader"
              :action="'/api/common/upload'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.icon" :src="form.icon" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="upload-tips">请上传大小不超过 5MB 格式为 png/jpg/jpeg 的文件</div>
          </div>
        </el-form-item>
        <el-form-item label="类型">
          <div class="checkbox-group">
            <el-checkbox v-model="form.isRelation" label="关系型">关系型</el-checkbox>
            <el-checkbox v-model="form.isNoRelation" label="非关系型">非关系型</el-checkbox>
            <el-checkbox v-model="form.isSingle" label="单机">单机</el-checkbox>
            <el-checkbox v-model="form.isDistributed" label="分布式">分布式</el-checkbox>
          </div>
        </el-form-item>
        <el-form-item label="数据库描述" prop="description">
          <el-input v-model="form.description" type="textarea" rows="4" placeholder="请输入数据库描述" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'LinSihanDatabase',
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      selection: [],
      // 总条数
      total: 1,
      // 数据库列表 - 使用模拟数据
      databaseList: [
        {
          productId: 100,
          dbName: 'mysql',
          icon: 'https://img.icons8.com/color/48/000000/mysql-logo.png',
          type: '关系型 单机',
          isRelation: true,
          isNoRelation: false,
          isSingle: true,
          isDistributed: false,
          description: 'MySQL是一个关系型数据库管理系统',
          remark: '关系型 单机'
        }
      ],
      // 弹出层标题
      dialogTitle: '',
      // 是否显示弹出层
      dialogVisible: false,
      // 表单参数
      form: {
        productId: '',
        dbName: '',
        icon: '',
        isRelation: false,
        isNoRelation: false,
        isSingle: false,
        isDistributed: false,
        description: '',
        remark: ''
      },
      // 表单校验规则
      rules: {
        dbName: [
          { required: true, message: '数据库名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '数据库名称长度不能超过50个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '数据库描述不能为空', trigger: 'blur' }
        ]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dbName: ''
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表
    getList() {
      this.loading = true
      // 模拟API调用延迟
      setTimeout(() => {
        // 根据搜索条件过滤数据
        if (this.queryParams.dbName) {
          const filtered = this.databaseList.filter(item => 
            item.dbName.toLowerCase().includes(this.queryParams.dbName.toLowerCase())
          )
          this.total = filtered.length
          this.loading = false
        } else {
          this.total = this.databaseList.length
          this.loading = false
        }
      }, 300)
    },
    // 格式化类型显示
    formatType(row) {
      const types = []
      if (row.isRelation) types.push('关系型')
      if (row.isNoRelation) types.push('非关系型')
      if (row.isSingle) types.push('单机')
      if (row.isDistributed) types.push('分布式')
      return types.join(' ')
    },
    // 搜索按钮点击事件
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置按钮点击事件
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        dbName: ''
      }
      this.getList()
    },
    // 选中事件处理
    handleSelectionChange(selection) {
      this.selection = selection
    },
    // 新增按钮点击事件
    handleAdd() {
      this.dialogTitle = '添加数据库产品'
      this.resetForm()
      this.dialogVisible = true
    },
    // 修改按钮点击事件
    handleUpdate() {
      if (this.selection.length !== 1) {
        this.$message.warning('请选择一条数据进行修改')
        return
      }
      this.handleEdit(this.selection[0])
    },
    // 编辑单个数据
    handleEdit(row) {
      this.dialogTitle = '修改数据库产品'
      this.form = { ...row }
      this.dialogVisible = true
    },
    // 删除按钮点击事件
    handleDelete() {
      if (this.selection.length === 0) {
        this.$message.warning('请选择至少一条数据进行删除')
        return
      }
      const productIds = this.selection.map(row => row.productId)
      this.$confirm(`确定要删除选中的 ${this.selection.length} 条数据吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.databaseList = this.databaseList.filter(item => !productIds.includes(item.productId))
        this.total = this.databaseList.length
        this.selection = []
        this.$message.success('删除成功')
      })
    },
    // 删除单条数据
    handleRemove(row) {
      this.$confirm(`确定要删除「${row.dbName}」吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.databaseList = this.databaseList.filter(item => item.productId !== row.productId)
        this.total = this.databaseList.length
        this.selection = []
        this.$message.success('删除成功')
      })
    },
    // 导出按钮点击事件
    handleExport() {
      this.$message.info('导出功能已触发')
    },
    // 分页大小改变
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize
      this.getList()
    },
    // 当前页数改变
    handleCurrentChange(pageNum) {
      this.queryParams.pageNum = pageNum
      this.getList()
    },
    // 关闭对话框
    handleClose() {
      this.dialogVisible = false
      this.resetForm()
    },
    // 重置表单
    resetForm() {
      this.form = {
        productId: '',
        dbName: '',
        icon: '',
        isRelation: false,
        isNoRelation: false,
        isSingle: false,
        isDistributed: false,
        description: '',
        remark: ''
      }
      if (this.$refs['form']) {
        this.$refs['form'].resetFields()
      }
    },
    // 提交表单
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 更新类型和备注
          const type = this.formatType(this.form)
          this.form.type = type
          this.form.remark = type
          
          if (this.form.productId) {
            // 修改操作
            const index = this.databaseList.findIndex(item => item.productId === this.form.productId)
            if (index > -1) {
              this.databaseList[index] = { ...this.form }
            }
            this.$message.success('修改成功')
            this.dialogVisible = false
          } else {
            // 新增操作
            // 生成一个简单的ID
            this.form.productId = Date.now()
            this.databaseList.push({ ...this.form })
            this.total = this.databaseList.length
            this.$message.success('新增成功')
            this.dialogVisible = false
          }
        }
      })
    },
    // 头像上传成功处理
    handleAvatarSuccess(res, file) {
      // 在模拟环境中使用本地图片URL
      this.form.icon = URL.createObjectURL(file.raw)
    },
    // 头像上传前处理
    beforeAvatarUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5
      const isImg = ['image/png', 'image/jpeg', 'image/jpg'].includes(file.type)
      if (!isImg) {
        this.$message.error('上传头像图片只能是 png/jpg/jpeg 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isImg && isLt5M
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.tool-bar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.upload-container {
  display: flex;
  flex-direction: column;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}

.upload-tips {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}

.checkbox-group {
  display: flex;
  gap: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>